package com.mooral.web.action.user;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.mooral.bean.User;
import com.mooral.bean.Voucher;
import com.mooral.context.Context;
import com.mooral.dataAccess.DataAccessConnection;
import com.mooral.web.action.MooralAction;

public class SaveAction extends MooralAction {

	@Override
	public ActionForward perform(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			Context context) throws Exception {
		
		DynaActionForm dform = (DynaActionForm) form;
		User user = (User) dform.get("user");
		String categoriesSelected[] = (String[])dform.get("categoriesSelected");
		Long userId = null;
		
		DataAccessConnection dataAccessConnection = context.getDataAccessConnection();

		try{
			dataAccessConnection.beginTransaction();
			
			dataAccessConnection.executeUpdate("insert into users (email,password,periodicity,created) values ('" + user.get("email")+ "','" + user.get("password") + "','"+user.get("periodicity")+"','"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Timestamp(System.currentTimeMillis())) +"')");
			
			ResultSet resultSet = dataAccessConnection.getResultSetQuery("select max(id) as maxId from users ");
			resultSet.next();
			userId = resultSet.getLong(1);

			for(String categoryId: categoriesSelected){
				dataAccessConnection.executeUpdate("insert into categories_users (user_id, category_id) values ("+userId.toString()+"," + categoryId + ")");
			}
			
			dataAccessConnection.commitTransaction();
		} catch (SQLException sqle){
			dataAccessConnection.rollbackTransaction();
		}
		
		// TODO QUE HACER CUANDO SE INSERTA Y QUE HACER CUANDO NO
		

		user.populate("select * from users where id = " +  userId);
		
		context.setUser(user);
		
		dataAccessConnection.disposeConnection();
		
		
		return mapping.findForward(ACTION_SUCCESS);
	}

/*	  public ActionErrors validate(
	      ActionMapping mapping, HttpServletRequest request ) {
	      ActionErrors errors = new ActionErrors();
	
	      if( get("") == null || getName().length() < 1 ) {
	        errors.add("name",new ActionMessage("error.name.required"));
	      }
	      
	
	      return errors;
	  }
*/
}
